package org.example.security;

import org.example.domain.Permission;
import org.example.domain.User;
import org.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userMapper.findByUsername(s);

        if (user != null) {
            //根据用户名查询当前用户所有权限
            List<Permission> permissionList = userMapper.findPermissionByUsername(s);

            //存放所有用户权限
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (Permission permission : permissionList) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermTag());
                authorities.add(grantedAuthority);
            }

            user.setAuthorities(authorities);
        }
        return user;
    }
}
